import React, { useState, useEffect } from 'react';
import { useModel } from 'umi';
import { Form, Button, Space, Notification } from 'antd';
import { goBack, componentsMap } from '@/utils/util';
import UploadList from '@/components/UploadList';
import FileList from '@/components/FileLists';
import API from '@/api/report.js';
import moment from 'moment';
const safeComponent = ({ children, id, readOnly }) => {
  const { initialState = {} } = useModel('@@initialState');
  const { orgName = '', username = '' } = initialState.info;
  const [SJYXCD, setSJYXCD] = useState([]);
  const [AQSJSB_SJLX, setAQSJSB_SJLX] = useState([]);
  const [SJJB, setSJJB] = useState([]);
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([]);

  const checkPhone = async (rule, value) => {
    if (!value) {
      return Promise.reject('请输入联系方式');
    } else {
      if (!/^[1][0-9]{10}$/.test(value)) {
        return Promise.reject('请输入正确的手机号码');
      } else {
        return Promise.resolve();
      }
    }
  };

  const baseInfo = [
    {
      label: '标题',
      name: 'title',
      type: 'input',
      rules: [
        {
          required: true,
          message: '请输入标题',
        },
      ],
      isremark: true,
    },
    {
      label: '上报单位',
      name: 'orgName',
      otherProps: {
        disabled: true,
      },
    },
    {
      label: '上报人',
      name: 'userName',
      otherProps: {
        disabled: true,
      },
    },
    {
      label: '上报时间',
      name: 'createTime',
      otherProps: {
        disabled: true,
      },
    },
    {
      label: '联系方式',
      name: 'phone',
      type: 'input',
      otherProps: {
        maxlength: 11,
      },
      rules: [
        {
          required: true,
          validator: checkPhone,
        },
      ],
      //11位校
    },
    {
      label: '备注说明',
      name: 'adress',
      type: 'textarea',
      isremark: true,
    },
  ];
  const safeInfo = [
    {
      label: '事件类型',
      name: 'eventType',
      type: 'select',
      otherProps: {
        options: AQSJSB_SJLX,
      },
      rules: [
        {
          required: true,
          message: '请选择事件类型',
        },
      ],
    },
    {
      label: '事件级别',
      name: 'eventLevel',
      type: 'select',
      otherProps: {
        options: SJJB,
      },
      rules: [
        {
          required: true,
          message: '请选择事件级别',
        },
      ],
    },
    {
      label: '事件影响程度',
      name: 'eventImpact',
      type: 'select',
      otherProps: {
        options: SJYXCD,
      },
      rules: [
        {
          required: true,
          message: '请选择事件影响程度',
        },
      ],
    },
    {
      label: '事件影响范围',
      name: 'eventScope',
      type: 'input',
      rules: [
        {
          required: true,
          message: '请填写事件影响范围',
        },
      ],
    },
    {
      label: '事件原因分析',
      name: 'eventWhy',
      type: 'textarea',
      isremark: true,
      rules: [
        {
          required: true,
          message: '请填写事件原因分析',
        },
      ],
    },
    {
      label: '事件处置',
      name: 'eventDispose',
      type: 'textarea',
      isremark: true,
      rules: [
        {
          required: true,
          message: '请填写事件处置',
        },
      ],
    },
  ];

  // 上传附件
  const uploadOptions = {
    fileTypes: [
      'application/doc',
      'application/pdf',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'image/jpg',
      'image/jpeg',
      'image/png',
    ],
    maxSize: 50,
    maxNum: 3,
    accept: [
      '.doc,.docx.,.pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.jpg,.jpeg,.png',
    ],
    acceptMessage: 'jpg/word/pdf',
  };

  // 获取下拉列表数据
  function initList() {
    API.dictItemList().then((res) => {
      if (res) {
        let _SJYXCD = [];
        let _AQSJSB_SJLX = [];
        let _SJJB = [];
        res.t.forEach((item) => {
          if (item.dictCode == 'AQSJSB_SJLX') {
            _AQSJSB_SJLX.push({
              label: item.dictItemName,
              value: item.dictItemType,
            });
          }
          if (item.dictCode == 'SJJB') {
            _SJJB.push({
              label: item.dictItemName,
              value: item.dictItemType,
            });
          }
          if (item.dictCode == 'SJYXCD') {
            _SJYXCD.push({
              label: item.dictItemName,
              value: item.dictItemType,
            });
          }
        });
        setSJYXCD(_SJYXCD);
        setAQSJSB_SJLX(_AQSJSB_SJLX);
        setSJJB(_SJJB);
      }
    });
  }

  // 获取详情
  const initDetail = () => {
    API.showReport({
      id,
    }).then((res) => {
      console.log(res);
      // if (res) {
      //   form.setFieldsValue({
      //     ...res.t,
      //   });
      //   setFileList(res.t.reportFileList);
      // }
      if (res?.t) {
        const {
          title,
          orgName,
          userName,
          createTime,
          phone,
          adress,
          eventType,
          eventLevel,
          eventImpact,
          eventScope,
          eventWhy,
          eventDispose,
        } = res.t;
        setFileList(res.t.reportFileList);
        form.setFieldsValue({
          title,
          orgName,
          userName,
          createTime: createTime.split(' ').shift(),
          phone,
          adress,
          eventType,
          eventLevel,
          eventImpact,
          eventScope,
          eventWhy,
          eventDispose,
        });
      }
    });
  };

  // 提交
  const submitFn = (value) => {
    const params = {
      eventDispose: value.eventDispose,
      eventImpact: value.eventImpact,
      eventLevel: value.eventLevel,
      eventScope: value.eventScope,
      eventType: value.eventType,
      eventWhy: value.eventWhy,
      phone: value.phone,
      title: value.title,
      adress: value.adress,
      reportFileList: value.reportFileList,
      reportType: '2',
    };
    console.log(params);
    let request = API.addReport;
    if (id) {
      params.id = id;
      request = API.updateReport;
    }
    const title = id ? '编辑' : '新增';
    request(params).then((res) => {
      if (res) {
        Notification.success({
          message: title + '成功',
        });
        goBack();
      }
    });
  };

  useEffect(() => {
    initList();
  }, []);

  useEffect(() => {
    if (id) {
      initDetail();
    } else {
      // form.setFieldsValue();
      form.setFieldsValue({
        orgName: orgName,
        userName: username,
        createTime: moment().format('YYYY-MM-DD'),
      });
    }
  }, [id]);

  return (
    <div className="main-x">
      <Form form={form} onFinish={submitFn}>
        <div className="base-title">基本信息</div>
        <div className="ant-form-inline form-x bgf">
          {baseInfo.map((item) => {
            return (
              <Form.Item
                key={item.name}
                label={item.label}
                name={item.name}
                className={item.isremark ? 'block' : ''}
                rules={item.rules}
              >
                {componentsMap(item.type, item.otherProps, readOnly)}
              </Form.Item>
            );
          })}
        </div>
        <div className="base-title mt20">安全事件信息</div>
        <div className="ant-form-inline form-x bgf">
          {safeInfo.map((item) => {
            return (
              <Form.Item
                key={item.name}
                label={item.label}
                name={item.name}
                className={item.isremark ? 'block' : ''}
                rules={item.rules}
              >
                {componentsMap(item.type, item.otherProps, readOnly)}
              </Form.Item>
            );
          })}
        </div>
        <div className="base-title mt20">附件信息</div>
        <div className="form-x bgf" style={{ paddingBottom: '16px' }}>
          {readOnly ? (
            <>
              <Form.Item label="附件信息" className="block">
                {
                  <FileList
                    fileList={fileList}
                    downloadUrl="/report/download"
                  />
                }
              </Form.Item>
            </>
          ) : (
            <>
              <Form.Item
                label="附件信息"
                extra="支持jpg/word/pdf格式,单个大小在50M以内"
                name="reportFileList"
                className="block"
              >
                <UploadList
                  uploadUrl="/report/fileUpload"
                  downloadUrl="/report/download"
                  options={uploadOptions}
                  defaultFiles={fileList}
                ></UploadList>
              </Form.Item>
            </>
          )}
        </div>
        <div className="footer-x max-x">{children}</div>
      </Form>
    </div>
  );
};
export default safeComponent;
